package web;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import orm.PMF;
import orm.Profile;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class BaseServlet extends HttpServlet {
	
	protected void checkSign(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		if (!userService.isUserLoggedIn()) {
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
		}

		/**
	    PersistenceManager pm = PMF.get().getPersistenceManager(); 
	    Query query = pm.newQuery(Profile.class);
	    query.setFilter("user == userParam");
	    query.declareParameters("String userParam");
	    try {
	    	List<Profile> profiles = (List<Profile>) query.execute(user);
	    	if (profiles != null && profiles.iterator().hasNext()) {
	    		Profile profile = profiles.get(0);
	    	    req.setAttribute("currentUser", user);
	    	}
	    } finally {
	    	query.closeAll();
	    }
	    */
	    
	    req.setAttribute("currentUser", userService.getCurrentUser());
	}
}
